package com.gengzp.ops.facade.impl;

import com.gengzp.common.constants.EnvironmentConstants;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.nacos.resp.SearchOnlineNacosInstanceResp;
import com.gengzp.common.utils.RestTemplateUtils;
import com.gengzp.ops.facade.INacosFacadeService;
import com.gengzp.ops.mapper.NacosConfigMapper;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.gengzp.common.constants.NacosApiUrlConstants.SEARCH_NACOS_ONLINE_SERVICE_INSTANCE_URL;

/**
 * @ClassName NacosFacadeServiceImpl
 * @Description nacos门面实现类
 * @Author gengzp
 * @Date 2025/6/1 19:33
 */
@Service
public class NacosFacadeServiceImpl implements INacosFacadeService {

    @Autowired
    private NacosConfigMapper nacosConfigMapper;

    @Autowired
    private Environment environment;

    @Override
    public List<String> searchOnlineInstanceUrlByServiceName(String serviceName) {
        // 从nacos查询在线的实例
        SearchOnlineNacosInstanceResp searchOnlineNacosInstanceResp = RestTemplateUtils.get(
                String.format("http://%s%s?serviceName=%s&clusterName=DEFAULT&groupName=%s&pageSize=1000&pageNo=1&namespaceId=%s",
                        searchCurrentNacosAddress(), SEARCH_NACOS_ONLINE_SERVICE_INSTANCE_URL, serviceName, searchCurrentNacosGroup(), searchCurrentNacosNamespace()),
                SearchOnlineNacosInstanceResp.class);
        if (CollectionUtils.isEmpty(searchOnlineNacosInstanceResp.getList())) {
            return Collections.emptyList();
        }
        return searchOnlineNacosInstanceResp.getList().stream()
                .map(v -> String.format("%s:%s", v.getIp(), v.getPort())).collect(Collectors.toList());
    }

    @Override
    public String searchCurrentNacosAddress() {
        return environment.getProperty(EnvironmentConstants.NACOS_ADDRESS);
    }

    @Override
    public String searchCurrentNacosGroup() {
        return environment.getProperty(EnvironmentConstants.NACOS_GROUP);
    }

    @Override
    public String searchCurrentNacosNamespace() {
        return environment.getProperty(EnvironmentConstants.NACOS_NAMESPACE);
    }

    @Override
    public Map<String, List<String>> searchNacosAddressMapByServiceNames(List<String> serviceNames) {
        if (CollectionUtils.isEmpty(serviceNames)) {
            throw BusinessException.get("服务名不能为空");
        }

        Map<String, List<String>> result = Maps.newHashMap();
        serviceNames.forEach(v -> result.put(v, searchOnlineInstanceUrlByServiceName(v)));

        return result;
    }

}
